<template>
  <div class="pages personDetail">
    <div class="pageLevel">
      <div class="form-content">
        <!-- 操作框 -->
        <div class="operationBox tableSearch">
          <el-button type="primary" @click="closeAdd" size="mini">返回</el-button>
        </div>
        <!-- 表单内容 -->
        <el-form
          :label-position="ruleForm.labelPosition"
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="120px"
          class="demo-ruleForm"
          size="small"
        >
          <div>
            <div class="rowtwo">
              <el-row class="rowtwo-form">
                <el-form-item label="广告标题" prop="title">
                  <el-input show-word-limit type="text" v-model="ruleForm.title" maxlength="30"></el-input>
                </el-form-item>
              </el-row>
              <el-row class="rowtwo-img">
                <el-form-item prop="picUrl" label="广告图片">
                  <div class="uploadTip">图片尺寸为1024*600，大小不超过15M</div>
                  <div :class="['imgbox',{'imgbox-v':!ruleForm.picUrl}]">
                    <img :src="ruleForm.picUrl" alt>
                  </div>
                  <el-upload
                    class="upload-demo"
                    action="1"
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :http-request="uploadSectionFile2"
                  >
                    <el-button class="upload-btn" size="small" type="primary">上传图片</el-button>
                  </el-upload>
                </el-form-item>
              </el-row>
            </div>
            <el-row style="width: 660px">
              <el-form-item label="广告有效期" prop="validityStart" class="inline-block">
                <el-date-picker
                  v-model="ruleForm.validityStart"
                  type="date"
                  placeholder="选择开始日期"
                  @change="checkTime"
                  :picker-options="pickerOptions"
                ></el-date-picker>
                <span>至</span>
              </el-form-item>
              <el-form-item prop="validityEnd" class="inline-block endTime">
                <el-date-picker
                  v-model="ruleForm.validityEnd"
                  type="date"
                  placeholder="选择结束日期"
                  @change="checkTime"
                  :picker-options="pickerOptions"
                ></el-date-picker>
              </el-form-item>
            </el-row>
            <el-row style="width: 600px">
              <el-form-item label="状态" prop="status">
                <el-radio v-model="ruleForm.status" label="0">启用</el-radio>
                <el-radio v-model="ruleForm.status" label="1">停用</el-radio>
              </el-form-item>
            </el-row>
            <el-row style="width: 600px">
              <el-button size="small" @click="closeAdd">取消</el-button>
              <el-button size="small" type="primary" @click="release">保存</el-button>
            </el-row>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import util from "@/util";
import s from "@/util/state";
import u from "@/util";
import {
  uploadFile,
  getFile,
  addPosSubScreen, // 新增
  updatePosSubScreen, // 编辑 dr= 0
  queryPosSubScreen // 查询
} from "@/api";
export default {
  computed: mapState(["merchantId", "path", "power"]),
  components: {},

  data() {
    return {
      clearable: false,
      id: "",
      time: "",
      ruleForm: {
        title: "",
        picUrl: "",
        validityStart: "",
        validityEnd: "",
        status: "0"
      },

      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        picUrl: [{ required: true, message: "请上传图片", trigger: "blur" }],
        validityStart: [
          {
            type: "date",
            required: true,
            message: "请选择开始日期",
            trigger: "change"
          }
        ],
        validityEnd: [
          {
            type: "date",
            required: true,
            message: "请选择结束日期",
            tigger: "change"
          }
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }]
      },
      radio: "",
      onlineClassList: [],
      selectClass: {},
      searchClassInput: "",
      currentPage: 1,
      pageSize: 20,
      totalItems: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()-24*60*60*1000;
        }
      },
      showUrl: ""
    };
  },
  created() {
    this.id = u.getQuery("id");
    this.status = u.getQuery("status");
    if (this.id != "") {
      queryPosSubScreen({ id: this.id }).then(res => {
        this.ruleForm = res.data;
      });
    } else {
      this.ruleForm.validityStart = new Date(new Date().toLocaleDateString()).getTime();
      this.ruleForm.validityEnd = Date.now() + 24 * 60 * 60 * 1000;
    }
  },
  methods: {
    goBack() {
      history.back();
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let postData = {
            shopId: this.merchantId,
            title: this.ruleForm.title,
            picUrl: this.ruleForm.picUrl,
            validityStart: this.ruleForm.validityStart,
            validityEnd: this.ruleForm.validityEnd,
            status: this.ruleForm.status
          };

          if (this.id != "") {
            postData.id = this.id;
            updatePosSubScreen(postData).then(res => {
              if (res.code == 200) {
                this.$message({
                  showClose: true,
                  message: "编辑成功",
                  type: "success"
                });

                history.back(-1);
                return false;
              }
            });
          } else {
            addPosSubScreen(postData).then(res => {
              if (res.code == 200) {
                this.$message({
                  showClose: true,
                  message: "新建成功",
                  type: "success"
                });

                history.back(-1);
                return false;
              }
            });
          }
        } else {
          this.$message({
            showClose: true,
            message: "请检查必填信息",
            type: "error"
          });
          return false;
        }
      });
    },

    // 上传图片之前验证图片格式
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 15;
      if (!isJPG) {
        this.$message.error("上传图片格式错误!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 15M!");
      }

      return isJPG && isLt2M;
    },
    //上传图片
    uploadSectionFile2(param) {
      var fileObj = param.file;
      var data = new FormData();
      data.append("file", fileObj);
      data.append("projectName", fileObj.name);
      uploadFile(data).then(res => {
        this.ruleForm.picUrl = `${getFile}?id=${res.data.id}`;
      });
    },

    closeAdd() {
      this.$confirm(
        "您确认要离开该页面吗- 您输入的数据可能不会被保存。",
        "确认关闭",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消"
        }
      )
        .then(() => {
          this.goBack();
        })
        .catch(() => {});
    },

    release() {
      if (!this.ruleForm.title) {
        this.$message({
          message: "请输入标题",
          type: "error"
        });
      } else if (!this.ruleForm.picUrl) {
        this.$message({
          message: "请上传图片",
          type: "error"
        });
      } else {
        this.submitForm("ruleForm");
      }
    },

    readioChange(row) {
      this.selectClass = row;
    },

    addOnlingCladdUrl() {
      this.ruleForm.linkUrl = this.selectClass.id;
      this.showUrl = this.selectClass.title;
      this.ruleForm.linkType = 1;
      this.dialogTableVisible_o = false;
    },
    addLinkUrl() {
      this.ruleForm.linkType = 0;
      this.showUrl = this.ruleForm.linkUrl;
      this.dialogTableVisible_o = false;
    },

    toPage() {
      this.getCourseList("");
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.radio = "";
      this.getCourseList("");
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.radio = "";
      this.getCourseList("");
    },

    searchClass() {
      this.getCourseList(this.searchClassInput);
    },
    checkTime() {
   
      if (!this.ruleForm.validityEnd) {
        return false;
      }
      if (!this.ruleForm.validityStart) {
        this.$message.error("开始日期不能为空");
      }
      if (this.ruleForm.validityEnd < this.ruleForm.validityStart) {
        this.$message.error("开始时间不能晚于结束时间");
        this.ruleForm.validityEnd = "";
      }
    }
  }
};
</script>
<style scoped>
.uploadTip {
  font-size: 12px;
  color: #868181;
}
.el-date-editor.el-input {
  margin: 0 20px 20px 0;
}
.rowtwo .rowtwo-form {
  width: 450px;
}
.imgbox {
  display: inline-block;
  border: 1px dashed #dcdfe6;
}
.imgbox-v {
  width: 200px;
  height: 200px;
}
.imgbox img {
  display: block;
  width: auto;
  height: 200px;
}
.upload-btn {
  width: 100%;
  margin: 10px 0;
}
.inline-block {
  display: inline-block;
}
</style>
<style lang="">
.inline-block.endTime .el-form-item__content {
  margin-left: 20px !important;
}
</style>


